package com.xuexiang.yoyo.sql.mapper;

import android.content.ContentValues;
import android.database.Cursor;

import com.xuexiang.yoyo.constant.HesAppStatic;
import com.xuexiang.yoyo.entity.Device;

import java.util.ArrayList;
import java.util.List;

public class DeviceMapper {
    public static final String TABLE = "device";
    public static final String CREATE_TABLE_SQL="CREATE TABLE "+ TABLE +"(device_code TEXT PRIMARY KEY," +
            "protocal TEXT ," +
            "communication TEXT," +
            "baud TEXT," +
            "createTime TEXT," +
            "username TEXT" +
            ");";
    public static Device queryByDeviceCode(String deviceCode){
        Cursor cursor = HesAppStatic.getmDataBaseOpenHelper().query(TABLE, "where username='" + HesAppStatic.getUsername() + "' and device_code='" + deviceCode + "'");
        Device device = null;
        while (cursor.moveToNext()) {
            device = new Device();
            device.setDeviceCode(cursor.getString(0));
        }
        cursor.close();
        return device;
    }

    public static void insert(Device device){
        delete(device.getDeviceCode());
        ContentValues deviceContentValues = new ContentValues();
        deviceContentValues.put("device_code", device.getDeviceCode());
        deviceContentValues.put("protocal", device.getProtocal());
        deviceContentValues.put("communication", device.getCommunication());
        deviceContentValues.put("baud", device.getBaud());
        deviceContentValues.put("createTime", device.getCreateTime());
        deviceContentValues.put("username", device.getUsername());
        HesAppStatic.getmDataBaseOpenHelper().insert(TABLE,deviceContentValues);
    }

    public static void delete(){
        HesAppStatic.getmDataBaseOpenHelper().delete(TABLE,"username='" + HesAppStatic.getUsername() + "'",null);
    }
    public static void delete(String deviceCode){
        HesAppStatic.getmDataBaseOpenHelper().delete(TABLE,"username='" + HesAppStatic.getUsername() + "' and device_code='"+deviceCode+"'",null);
    }
    public static List<Device> queryAll(){
        Cursor cursor = HesAppStatic.getmDataBaseOpenHelper().query(TABLE, "where username='" + HesAppStatic.getUsername() + "'");
        List<Device> resultList = new ArrayList<>();
        while (cursor.moveToNext()) {
            Device device = new Device();
            device.setDeviceCode(cursor.getString(0));
            device.setProtocal(cursor.getString(1));
            device.setCommunication(cursor.getString(2));
            device.setBaud(cursor.getString(3));
            device.setCreateTime(cursor.getString(4));
            device.setUsername(cursor.getString(5));
            resultList.add(device);
        }

        cursor.close();
        return resultList;
    }

}
